package com.zlq.cn.bootstrap;

import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 参数校验
 *
 * @author zhoucl
 * @date 2021/7/6 11:11
 */
@Component
public class ValidateBootstrap {

    /**
     * 校验工具
     */
    private static Validator validator;

    public ValidateBootstrap(Validator validator) {
        ValidateBootstrap.validator = validator;
    }

    /**
     * 参数校验
     *
     * @param data 校验对象
     * @return 返回null校验通过；不为null返回校验错误信息
     */
    public static String validator(Object data, Class<?>... groups) {
        Set<ConstraintViolation<Object>> validate = validator.validate(data, groups);
        if (!validate.isEmpty()) {
            return validate.stream()
                    .map(ConstraintViolation::getMessage)
                    .collect(Collectors.joining("\n"));
        }
        return null;
    }
}

